<!--
author:        hejy <silentmanager@163.com>
date:          2024-11-01 00:09:19
component:     index
Copyright © YourCompanyName All rights reserved
创建订单
-->

<template>
  <div>
    <!-- 客户信息 -->
    <el-card style="margin-bottom: 24px">
      <template #header>
        <div class="first_card_header">
          <span>客户信息</span>
          <div>
            <el-button type="success" :disabled="!lock" @click="handleUnlock"
              >录单保护解除申请</el-button
            >
            <el-tooltip
              class="box-item"
              content="录单保护解除申请以站内信方式，拒绝或统一，假设客户下单并且在7天内另一个业务员进行下单操作，这个时候会点亮录单保护解除申请按钮，经理进行审核后方可提交订单"
              placement="bottom"
            >
              <el-button>录单情况说明</el-button>
            </el-tooltip>
          </div>
        </div>
      </template>
      <el-form ref="firstFormRef" :rules="firstRules" :inline="true" :model="firstFormData">
        <el-form-item style="margin-right: 10px" label="客户手机" prop="customerPhone">
          <el-input
            style="width: 240px"
            v-model="firstFormData.customerPhone"
            placeholder="请输入客户手机"
            clearable
          />
        </el-form-item>
        <span
          style="
            position: relative;
            bottom: 10px;
            color: #409eff;
            font-size: 12px;
            margin-right: 12px;
            cursor: pointer;
          "
          @click="handleSearchCustomer"
        >
          <Icon icon="ep:search" :size="11" class="mr-0px" />查询客户
        </span>
        <el-form-item label="客户姓名" prop="customerName">
          <el-input
            style="width: 240px"
            v-model="firstFormData.customerName"
            placeholder="请输入客户姓名"
            clearable
          />
        </el-form-item>

        <el-form-item style="margin-right: 10px" label="详细地址" prop="address">
          <el-input
            style="width: 240px"
            v-model="firstFormData.address"
            placeholder="请输入详细地址"
            clearable
          />
        </el-form-item>

        <el-form-item label="客户类型" prop="customerType">
          <el-select
            :disabled="true"
            style="width: 240px"
            v-model="firstFormData.customerType"
            placeholder="请选择客户类型"
          >
            <el-option
              v-for="item in CustomerTypeOptions"
              :key="item.label"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="firstFormData.gender">
            <el-radio value="男">男</el-radio>
            <el-radio value="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number
            style="width: 240px"
            v-model="firstFormData.age"
            placeholder="请输入年龄"
            :min="0"
            :max="154"
            :precision="0"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 套餐信息 -->
    <el-card style="margin-bottom: 24px">
      <template #header>
        <div class="second_card_header">
          <div>
            <span>套餐信息</span>
            <span>(金额单位：元)</span>
          </div>
          <el-button type="success" @click="showDialog">添加套餐</el-button>
        </div>
      </template>
      <el-table show-summary :summary-method="getSummaries" :data="tableData" style="width: 100%">
        <el-table-column label="商品名称" prop="packageName" />
        <el-table-column width="180px" label="数量" prop="num">
          <template #default="scope">
            <el-input-number
              @change="handleChangeNum(scope.row)"
              v-model="scope.row.num"
              :min="1"
            />
          </template>
        </el-table-column>
        <el-table-column label="箱数" prop="packageCount">
          <template #default="scope">
            <div> {{ calculateCount(scope.row, scope.row.originPackageCount) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="瓶数" prop="bottleCount">
          <template #default="scope">
            <div> {{ calculateCount(scope.row, scope.row.originBottleCount) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="套餐单价" prop="packagePrice" />
        <el-table-column label="套餐营业额" prop="packageRevenue">
          <template #default="scope">
            <div> {{ calculateTotalTurnover(scope.row) }}</div>
          </template>
        </el-table-column>

        <el-table-column width="180px" label="套餐加价金额" prop="packageExtra">
          <template #default="scope">
            <el-input-number v-model="scope.row.packageExtra" :min="0" />
          </template>
        </el-table-column>
        <el-table-column width="180px" label="运费加价金额" prop="shippingExtra">
          <template #default="scope">
            <el-input-number v-if="!isRemote" v-model="scope.row.shippingExtra" :min="0" />
            <span v-if="isRemote">{{
              calculateCount(scope.row, scope.row.originBottleCount) * 10 || 0
            }}</span>
          </template>
        </el-table-column>
        <el-table-column width="180px" label="预付款" prop="prepayment">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.prepayment"
              :min="0"
              :max="calculateTotal(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="待收尾款" prop="pendingPayment">
          <template #default="{ row }">
            <span>{{ balancePayment(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="套餐总金额" prop="packageTotal">
          <template #default="{ row }">
            <span>{{ calculateTotal(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button link type="danger" @click="handledismiss(scope.row.packageId)"
              >移除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 订单信息 -->
    <el-card style="margin-bottom: 24px">
      <template #header>
        <div class="third_card_header">订单信息</div>
      </template>
      <FormComponent ref="formRef2" :config="formConfig2"
    /></el-card>

    <!-- 确认 -->
    <el-card>
      <div class="lastCard">
        <el-button
          @click="handleSave"
          v-hasPermi="['bms:order-info:createbtn']"
          :disabled="lock"
          type="success"
          >保存</el-button
        >
        <el-button @click="handleReset" type="success">重置</el-button>
      </div>
    </el-card>
    <!-- 占用库存订单列表弹窗 -->
    <SetMenu
      v-model:visible="isDialogVisible"
      :tableData="tableData"
      @update-data="updateParentData"
    />
  </div>
</template>
<script lang="ts" setup>
import SetMenu from './components/setMenu.vue'
import FormComponent from '@/components/FormComponent/index.vue'
import { getIntDictOptions } from '@/utils/dict'
import {
  contactSimpleAllListUser,
  createOrderInfo,
  CreateOrderInfoReq,
  lockStatus,
  queryByPhone,
  simpleListUser
} from '@/api/order/create'
import { CustomerTypeOptions } from '@/mock'
import { defaultProps } from '@/utils/tree'
import { useDeptList } from '@/hooks/useDeptList'
import { useRouter } from 'vue-router'
import { requestUnLock } from '@/api/order/all'
import { TableColumnCtx } from 'element-plus'
const router = useRouter()
const message = useMessage()
// ----------------------------- 占用库存订单列表弹窗状态 -----------------------------
const isDialogVisible = ref<boolean>(false) // 定义对话框可见性的状态
// 显示弹窗的处理函数
const showDialog = () => {
  isDialogVisible.value = true // 显示弹窗
}
// ==================== 表单1  ====================
const firstFormRef = ref(null)
// 是否偏远地区
const isRemote = ref(false)
const firstRules = reactive({
  // 手机号校验
  customerPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^[1][3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  customerName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { pattern: /^[1-9]\d*$/, message: '请输入有效的年龄（正整数）', trigger: 'blur' }
  ]
})
const lock = ref(false)
const customer = ref({
  customerId: '',
  customerMobile: ''
})
const firstFormData = ref<Record<string, any>>({
  customerId: 0,
  customerPhone: '',
  customerName: '',
  address: '',
  customerType: '',
  gender: '',
  age: 0
})
const handleSearchCustomer = async () => {
  try {
    const isLock = await lockStatus(firstFormData.value.customerPhone)
    lock.value = isLock.data
    const res = await queryByPhone({ phone: firstFormData.value.customerPhone })
    firstFormData.value.address = res.detailAddress
    firstFormData.value.customerName = res.name
    firstFormData.value.customerType = res.level
    firstFormData.value.gender = res.sex
    firstFormData.value.age = res.age
    firstFormData.value.customerId = res.id
    customer.value = {
      customerId: res.id,
      customerMobile: res.mobile
    }
  } catch (e) {
    console.error(e)
  }
}
const handleUnlock = async () => {
  try {
    const res = await requestUnLock(customer.value)
    if (res.code === 0) {
      message.success('申请解锁成功!')
    }
  } catch (e) {
    console.error(e)
  }
}

watch(
  () => history.state,
  (newParams) => {
    if (newParams?.data) {
      firstFormData.value = { ...newParams.data }
      lock.value = newParams.data.lock
    }
  },
  { immediate: true }
)
watch(
  () => firstFormData.value.address,
  (newAddress) => {
    if (newAddress.includes('内蒙古') || newAddress.includes('新疆')) {
      isRemote.value = true
    } else {
      isRemote.value = false
    }
    console.log(isRemote, '====>isRemote')
  }
)
// ==================== 表单2  ====================
const { deptList } = useDeptList()
const userList = ref<{ label: string; value: number }[]>([])
const formRef2 = ref<InstanceType<typeof FormComponent>>()

const formConfig2 = ref([
  {
    label: '对接班组',
    prop: 'teamId',
    type: 'tree',
    options: {
      placeholder: '请选择所属组织',
      style: 'width: 240px',
      data: deptList,
      props: defaultProps,
      nodeKey: 'id',
      checkStrictly: true
    }
  },
  {
    label: '对接人',
    prop: 'contactId',
    type: 'select',
    options: {
      placeholder: '请选择对接人',
      style: 'width: 240px',
      options: userList,
      props: {
        label: 'nickname',
        value: 'id'
      }
    }
  },
  {
    label: '发货方式',
    prop: 'deliveryMethod',
    type: 'select',
    options: {
      placeholder: '请选择发货方式',
      style: 'width: 240px',
      options: getIntDictOptions('bms_delivery_type')
    }
  },
  {
    label: '订单备注',
    prop: 'orderNote',
    type: 'input',
    options: { placeholder: '请输入订单备注', style: 'width: 240px' }
  }
])
const simpleListUserFn = async (deptId: string) => {
  try {
    if (!deptId) {
      return
    }
    const res = await contactSimpleAllListUser({ deptId })
    userList.value = res.map((item) => {
      return {
        label: item.nickname,
        value: item.id
      }
    })
  } catch (e) {
    console.error(e)
  }
}
watch(
  [() => formRef2.value?.formData.teamId],
  ([newTeam]) => {
    formRef2.value?.setSingleData('contactId', '')
    simpleListUserFn(newTeam)
  },
  { deep: true }
)
// 保存函数
const handleSave = async () => {
  try {
    // @ts-ignore
    await firstFormRef.value.validate()
    const data = {
      ...firstFormData.value,
      ...formRef2.value?.formData,
      packageInfo: tableData.value,
      department: formRef2.value?.formData.teamId
    }
    const res = await createOrderInfo(data as CreateOrderInfoReq)
    if (res.code === 0) {
      router.push('/order/all')
    }
  } catch (e) {
    console.error(e)
  }
}
const handleReset = () => {
  firstFormData.value = {
    customerId: 0,
    customerPhone: '',
    customerName: '',
    address: '',
    customerType: '',
    gender: '',
    age: 0
  }
  tableData.value = []
  formRef2.value?.setData({})
}

// ==================== 表格  ====================
export interface TableDataModel {
  bottleCount: number //瓶数
  num: number //数量
  packageCount: number //箱数
  packageId: number //套餐ID
  packagePrice: number //套餐单价
  packageTotal: number //套餐总额
  packageTurnover: number //套餐营业额
  pendingPayment: number //待收尾款
  prepayment: number //预付款
  shippingExtra: number //运费加价
  packageExtra: number //套餐加价
  packageName: string //套餐名
  originBottleCount: number
}

interface SummaryMethodProps<T = TableDataModel> {
  columns: TableColumnCtx<T>[]
  data: T[]
}

// 数据
const tableData = ref<TableDataModel[]>([])
// 弹窗更新选择套餐内容
const updateParentData = (newData: TableDataModel[]) => {
  tableData.value = newData // 更新父组件的数据
}
// 计算展示的套餐营业额
const calculateTotalTurnover = (row: TableDataModel) => {
  return row.num * row.packagePrice
}
// 计算展示的套餐总金额
const calculateTotal = (row: TableDataModel) => {
  if (isRemote.value) {
    return (
      row.num * row.packagePrice +
        row.packageExtra +
        calculateCount(row, row?.originBottleCount) * 10 || 0
    )
  }
  return row.num * row.packagePrice + row.packageExtra + row.shippingExtra
}
// 计算展示的箱数和瓶数
const calculateCount = (row: TableDataModel, value: number) => {
  return row.num * value
}
// 计算展示的代收款
const balancePayment = (row: TableDataModel) => {
  return row.num * row.packagePrice + row.packageExtra + row.shippingExtra - row.prepayment
}
// 移除套餐
const handledismiss = (id: number) => {
  tableData.value = tableData.value.filter((item) => item.packageId !== id)
}
const handleChangeNum = (row: TableDataModel) => {
  if (!isRemote.value) {
    return
  }
  const index = tableData.value.findIndex((item) => item.packageId === row.packageId)
  if (index !== -1) {
    // 直接替换对象，触发视图更新
    tableData.value[index] = {
      ...tableData.value[index],
      //@ts-ignore
      shippingExtra: calculateCount(row, row.originBottleCount) * 10
    }
  }
}

// 合计行计算
const getSummaries = (param: SummaryMethodProps) => {
  const { columns } = param
  const sums: (string | VNode)[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = h('div', { style: { textDecoration: 'underline' } }, ['总计'])
      return
    }
    if (index === columns.length - 1) {
      sums[columns.length - 1] = h('div', null, '')
      return
    }

    const values = tableData.value.map((item) => {
      if (column.property === 'packageCount') {
        //@ts-ignore
        return calculateCount(item, item.originPackageCount)
      }
      if (column.property === 'bottleCount') {
        //@ts-ignore
        return calculateCount(item, item.originBottleCount)
      }
      if (column.property === 'packageTotal') {
        // 套餐总金额计算
        return calculateTotal(item)
      }
      if (column.property === 'pendingPayment') {
        // 待收尾款计算
        return balancePayment(item)
      }
      if (column.property === 'packageRevenue') {
        return calculateTotalTurnover(item)
      }
      return Number(item[column.property])
    })
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)}`
    } else {
      sums[index] = 'N/A'
    }
  })
  return sums
}
</script>
<style scoped lang="scss">
.first_card_header {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
.second_card_header {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  & > div:first-child {
    & > span:first-child {
      color: #404145;
      font-size: 14px;
      font-weight: 500;
      margin-right: 6px;
    }
    & > span:last-child {
      font-size: 10px;
      color: #e1e2e0;
    }
  }
}
.lastCard {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
</style>
